<?php
global_config::get_instance()->add_server_class("SoapCluster","soap_cluster");
class soap_cluster
{
	/**
	 * Items
	 *
	 * @var soap_array_of_int
	 */
	public $Items = array();

	public function save_to_db ($clusterisation_result_id){
		$cluster = new cluster();
		$array_cross = array();
		$dba = db_adapter::get_instance();
		foreach ($this->Items->as_array() as  $chain) {
			$cluster_chain= new cluster_chain();
			$criteria = new query_criteria();
			$criteria->add_criterion($cluster_chain->chain_id,criterion_type::$equal,$chain);
			$cluster_chain_list = $dba->get_list($cluster_chain,$criteria);
			$cluster_array = array();
			while ($cluster_chain_item = $cluster_chain_list->get_next()){
				$cluster_array[]=$cluster_chain_item->cluster_id->get_value();
			}
			$array_cross = !empty($array_cross)? array_intersect($array_cross, $cluster_array) : $array_cross = $cluster_array;

		}
		$temp_array = array();
		foreach ($array_cross as $cluster_id){
			$cluster = new cluster();
			$criteria->reset_criteria();
			$criteria->add_criterion($cluster->cluster_id,criterion_type::$equal, $cluster_id);
			$dba->load($cluster,$criteria);
			if($cluster->chain_count->get_value()==count($this->Items->as_array())){
				$temp_array[]=$cluster_id;
			}
		}

		if (empty($temp_array)){
			$cluster = new cluster();
			$cluster->chain_count->set_value(count($this->Items->as_array()));
			$dba->save($cluster);
			$cluster_id =$cluster->cluster_id->get_value();
				
			foreach ($this->Items->as_array() as $chain_id){
				$cluster_chain = new cluster_chain();
				$cluster_chain->cluster_id->set_value($cluster_id);
				$cluster_chain->chain_id->set_value($chain_id);
				$dba->save($cluster_chain);
			}
				
		}else{
			$cluster_id = current($temp_array);
		}
		return $cluster_id;
	}
}
?>